<template>
    <eui-page-frame :topHeight="250" :bottomHeight="90" withOutBorder="true">
        <template #top>
            <view class="content-img">
                <eui-navbar ref="euiNavBar" :title="title" :storeName="getRelatedName('rdsStores', sUserStore)"
                    :storeId="sUserStore" :displayable="true" color="#000000" backgroundColor="#FFFFFF">
                    <template v-slot:popupContent>
                        <view class="custom-menu">
                            <view class="popup-icon-btn icon_new_count" @tap="onClickSubmitDetail">
                                <icon class="icon enjoyIcon icon-buhuolishi-copy" />
                                <text>提交记录</text>
                            </view>
                        </view>
                    </template>
                </eui-navbar>
                <view class="top-view">
                    <eui-search-bar ref="RdsSearchBar" placeholder="请输入商品编码、条码" @confirm="searchConfirm"
                        v-model="searchText" radius="30" :focus="true"
                        :displayable="mainData.c_status !== '0' || mainData.c_approve_status !== '1'" />
                </view>
            </view>
        </template>
        <eui-page-content>
            <view class="footer-view">
                <view v-show="!showDiff">
                    <eui-card title="基本信息" showTitleLine="true" top-margin="0" h-padding="20" type="upDownSingle">
                        <template v-slot:content>
                            <view class="m-main-top">
                                <eui-text v-model="mainData.c_id" type="name" title="验收单号" occupy />
                                <eui-text v-model="mainData.c_provider" type="titlename" title="供应商"
                                    :name="getRelatedName('rdsProviders', mainData.c_provider)" occupy />
                            </view>
                        </template>
                        <view class="m-main-top">
                            <eui-text v-model="c_order_n_total" type="price" title="订货正品数量" />
                            <eui-text v-model="c_order_sku" type="name" title="订货品种数" />
                            <eui-text v-model="c_order_n_free_total" type="price" title="订货赠品数量" />
                            <eui-text value="" type="name" title="" />
                            <eui-text v-model="c_n_rec_total" type="price" title="已收正品数量" />
                            <eui-text v-model="c_sku_rec_total" type="name" title="已收品种数" />
                            <eui-text v-model="c_n_rec_free_total" type="price" title="已收赠品数量" />
                        </view>
                    </eui-card>
                    <eui-card title="当前商品" showTitleLine="true" h-padding="20">
                        <view @click="onClickGdsInfo(currentGds)">
                            <view class="m-main-top">
                                <eui-text
                                    :value="currentGds.c_gcode ? '[' + currentGds.c_gcode + ']' + currentGds.c_gname : ''"
                                    type="name" title="商品" occupy />
                                <eui-text v-model="currentGds.c_barcode" type="name" title="条码" />
                                <eui-text v-model="currentGds.c_order_pack" type="slash" :name="currentGds.c_order_unit"
                                    title="含量/单位" />
                                <eui-text v-model="currentGds.c_n_confirm" type="price" title="订货数量" :precision="3" />
                                <eui-text v-model="currentGds.c_n_free_confirm" type="price" title="赠品数量(订)"
                                    :precision="3" />
                                <eui-text v-model="currentGds.c_n" type="price" title="收货数量" :precision="3" />
                                <eui-text v-model="currentGds.c_n_free" type="price" title="赠品数量(收)" :precision="3" />
                                <eui-text v-model="currentGds.c_product_dt" type="date" title="生产日期" />
                                <eui-text v-model="currentGds.c_expired_dt" type="date" title="限用日期" />
                                <eui-text v-model="currentGds.c_serial_no" type="name" title="批号/串码" occupy />
                            </view>
                        </view>
                    </eui-card>
                </view>
                <view v-if="!showDiff">
                    <eui-card title="商品验收" showTitleLine="true" h-padding="20" type="detail">
                        <eui-swipe-action>
                            <view :id="`item-${index}`" v-for="(item, index) in listManager" :key="index"
                                @click="onClickGdsInfo(item, index)" style="background-color:#ffffff">
                                <eui-swipe-actionitem :right-options="options"
                                    :disabled="mainData.c_status !== '0' || mainData.c_approve_status !== '1'"
                                    show="none" :auto-close="true" @change="change" @click="bindClick($event, index)">
                                    <view class="m-list-top">
                                        <eui-text :value="`[${item.c_gcode}]${item.c_gname}`" type="name"
                                            :title="`${index + 1}. 商品`" occupy />
                                        <eui-text v-model="item.c_barcode" type="name" title="条码" />
                                        <eui-text v-model="item.c_order_pack" type="slash" :name="item.c_order_unit"
                                            title="含量/单位" />
                                        <!-- <eui-text v-model="item.c_at_pay_order" type="price" title="订货结算额" />
                            <eui-text v-model="item.c_at_pay" title="收货结算额" type="price" />
                            <eui-text :value="item.c_n_pack" :name="item.c_n_odd" type="rdsslash" title="收货件/零数" /> -->
                                        <eui-text v-model="item.c_n_confirm" type="price" title="订货数量" />
                                        <eui-text v-model="item.c_n_free_confirm" type="price" title="赠品数量(订)" />
                                        <eui-text v-model="item.c_n" type="price" title="收货数量"
                                            :valueStyle="(item.c_n !== 0 && item.c_n_confirm !== item.c_n) ? 'color: red' : 'color : black'" />
                                        <eui-text v-model="item.c_n_free" type="price" title="赠品数量(收)" />
                                        <!-- <eui-text :value="item.c_od_day + getDictName('保质期单位', item.c_od_unit)" type="name"
                                title="保质期" /> -->
                                        <!-- <eui-text v-model="item.c_pt_pay" type="price" title="结算价" /> -->
                                        <eui-text v-model="item.c_product_dt" type="date" title="生产日期" />
                                        <eui-text v-model="item.c_expired_dt" type="date" title="限用日期" />
                                        <eui-text v-model="item.c_serial_no" type="name" title="批号/串码" occupy />
                                        <eui-text v-model="item.c_note" type="name" v-if="item.c_note" title="备注" />
                                        <!-- <eui-text v-model="JSON.parse(item.c_err_msg)[0].c_msg_err" type="name"
                                        v-if="item.c_err_msg" title="错误" style="white-space: pre-wrap;color: red;"
                                        occupy /> -->
                                    </view>
                                </eui-swipe-actionitem>
                            </view>
                        </eui-swipe-action>
                        <view v-if="listManager.length === 0">
                            <image src="@/static/img/no_data.png" mode="aspectFit" class="image-min" />
                            <view class="no-data-text">暂无数据</view>
                        </view>
                    </eui-card>
                </view>
                <view v-show="showDiff">
                    <eui-card title="商品验收差异" showTitleLine="true" h-padding="20" type="detail">
                        <view :id="`item-${index}`" v-for="(item, index) in diffListManager" :key="index"
                            @click="onClickGdsInfo(item, index)">
                            <view class="m-list-top">
                                <eui-text :value="'[' + item.c_gcode + ']' + item.c_gname" type="name"
                                    :title="index + 1 + '. 商品'" occupy />
                                <eui-text v-model="item.c_barcode" type="name" title="条码" />
                                <eui-text v-model="item.c_order_pack" type="slash" :name="item.c_order_unit"
                                    title="含量/单位" />
                                <eui-text v-model="item.c_n_confirm" type="price" title="订货数量" />
                                <eui-text v-model="item.c_n_free_confirm" type="price" title="赠品数量(订)" />
                                <eui-text v-model="item.c_n" type="price" title="收货数量" valueStyle="color: red;" />
                                <eui-text v-model="item.c_n_free" type="price" title="赠品数量(收)" />
                                <eui-text v-model="item.c_product_dt" type="date" title="生产日期" />
                                <eui-text v-model="item.c_expired_dt" type="date" title="限用日期" />
                                <eui-text v-model="item.c_serial_no" type="name" title="批号/串码" occupy />
                                <eui-text v-model="item.c_note" type="name" v-if="item.c_note" title="备注" />
                                <!-- <eui-text v-model="JSON.parse(item.c_err_msg)[0].c_msg_err" type="name"
                                v-if="item.c_err_msg" title="错误" style="white-space: pre-wrap;color: red;" occupy /> -->
                            </view>
                        </view>
                        <view v-if="diffListManager.length === 0">
                            <image src="@/static/img/no_data.png" mode="aspectFit" class="image-min" />
                            <view class="no-data-text">暂无数据</view>
                        </view>
                    </eui-card>
                </view>
            </view>
        </eui-page-content>
        <template #bottom>
            <view class="bt-button">
                <eui-button type="max" single-tag="showDiff" title="显示差异" v-show="!showDiff"
                    @buttonClick="buttonClick" />
                <eui-button type="max" single-tag="showDiff" title="显示原始" v-show="showDiff"
                    @buttonClick="buttonClick" />
                <eui-button type="max" single-tag="detail" title="收货详情" :disabled="mainData.c_status !== '0'"
                    @buttonClick="buttonClick" />
                <eui-button type="max" single-tag="submit" title="提交"
                    :disabled="['3', '9'].includes(mainData.c_status) || mainData.c_approve_status !== '1'"
                    @buttonClick="buttonClick" />
            </view>
        </template>
    </eui-page-frame>
    <eui-popup ref="gdsPopup" background-color="#f8f8f8" type="bottom" :safe-area="true" @change="gdsPopupChange"
        borderRadius="10px 10px 0 0" :mask-click="false">
        <view class="popup-content">
            <view class="popup-title">{{ mainData.c_status === '0' ? '编辑' : '详情' }}</view>
            <view class="m-list-top">
                <eui-text :value="'[' + currentGds.c_gcode + ']' + currentGds.c_gname" type="name" title="商品" occupy />
                <eui-text v-model="currentGds.c_barcode" type="name" title="条码" />
                <eui-text v-model="currentGds.c_order_pack" type="slash" :name="currentGds.c_order_unit"
                    title="含量/单位" />
                <!-- <eui-text v-model="currentGds.c_at_pay_order" type="price" title="订货结算额" /> -->
                <eui-text v-model="currentGds.c_n_confirm" type="price" title="订货数量" :precision="3" />
                <eui-text v-model="currentGds.c_n_free_confirm" type="price" title="赠品数量" :precision="3" />
                <!-- <eui-text v-model="currentGds.c_at_pay" title="收货结算额" type="price" /> -->
                <eui-text :value="currentGds.c_n_pack" type="price" title="件数"
                    v-if="(sysConfig.inputType === '1') && (!(currentGds.c_order_pack > 1) || (mainData.c_status !== '0' || mainData.c_approve_status !== '1'))" />
                <eui-text :value="currentGds.c_n_odd" type="price" title="零数"
                    v-if="(sysConfig.inputType === '1') && (!(currentGds.c_order_pack > 1) || (mainData.c_status !== '0' || mainData.c_approve_status !== '1'))" />
                <eui-text :value="currentGds.c_n_input" type="price" title="包装数" :precision="3"
                    v-if="(sysConfig.inputType === '2') && (!(currentGds.c_order_pack > 1) || (mainData.c_status !== '0' || mainData.c_approve_status !== '1'))" />
                <eui-text :value="currentGds.c_od_day || 0 + getDictName('保质期单位', currentGds.c_od_unit)" type="name"
                    title="保质期" />
            </view>
            <view class="m-list-top" v-if="mainData.c_status !== '0' || mainData.c_approve_status !== '1'">
                <eui-text :value="currentGds.c_n" type="price" title="数量" :precision="3" />
                <eui-text :value="currentGds.c_n_free" type="price" title="赠品数量" :precision="3" />
                <eui-text :value="currentGds.c_product_dt" type="date" title="生产日期" />
                <eui-text :value="currentGds.c_expired_dt" type="date" title="限用日期" />
                <eui-text :value="currentGds.c_serial_no" type="name" title="批号" />
                <eui-text :value="currentGds.c_note" type="name" title="备注" />
            </view>
            <view v-if="mainData.c_status === '0' && mainData.c_approve_status === '1'">
                <eui-card-input v-model="currentGds.c_n_pack" title="件数" type="number" isBlur fieldName="c_n_pack"
                    @confirm="validateDetail" ref="cardNPackInput" placeholder="请输入件数"
                    v-if="currentGds.c_order_pack > 1 && sysConfig.inputType === '1'" id="c_n_pack" />
                <eui-card-input v-model="currentGds.c_n_odd" title="零数" type="number" isBlur fieldName="c_n_odd"
                    @confirm="validateDetail" ref="cardNOddInput" placeholder="请输入零数"
                    v-if="currentGds.c_order_pack > 1 && sysConfig.inputType === '1'" id="c_n_odd" />
                <eui-card-input v-model="currentGds.c_n_input" title="包装数" type="number" isBlur fieldName="c_n_input"
                    @confirm="validateDetail" ref="cardNIptInput" placeholder="请输入包装数"
                    v-if="currentGds.c_order_pack > 1 && sysConfig.inputType === '2'" id="c_n_input" />
                <eui-card-input v-model="currentGds.c_n" title="数量" type="number" isBlur fieldName="c_n" :focus="true"
                    @confirm="validateDetail" ref="cardRecNInput" placeholder="请输入收货数量" required
                    :style="currentGds.c_n < 0 ? 'color: red' : 'color: black'" singleTag="c_n" id="c_n" />
                <eui-card-input v-model="currentGds.c_n_free" title="赠品数量" type="number" isBlur fieldName="c_n_free"
                    @confirm="validateDetail" ref="cardNFreeInput" placeholder="请输入赠品数量" id="c_n_free" />
                <eui-card-input v-model="currentGds.c_serial_no" title="批号/串码" type="text" ref="serialNoInput"
                @confirm="validateDetail" isBlur id="c_serial_no" fieldName="c_serial_no" />
                <eui-card-input v-model="currentGds.c_product_dt" title="生产日期" type="date" @input="productDtChanged"
                    ref="productDtInput" rightIconType="clear" @iconClick="clear" singleTag="c_product_dt" />
                <eui-card-input v-model="currentGds.c_expired_dt" title="限用日期" type="date" @input="expiredDtChanged"
                    ref="expiredDtInput" rightIconType="clear" @iconClick="clear" singleTag="c_expired_dt" />
                <!-- <eui-card-input v-model="currentGds.c_pt_pay" title="结算价" type="number" isBlur
                            fieldName="c_pt_pay" @confirm="validateDetail" ref="cardPtPayInput"
                            :displayable=c_disabled /> -->
                <eui-card-input v-model="currentGds.c_note" title="备注" type="text" fieldName="c_note" maxlength="300"
                    id="c_note" />
            </view>
            <view class="bt-button">
                <eui-button type="max2" single-tag="cancel" title="关闭" @buttonClick="buttonClick" />
                <eui-button type="max" single-tag="submit3" title="确认" @buttonClick="buttonClick"
                    :disabled="mainData.c_status !== '0' || mainData.c_approve_status !== '1'" />
            </view>
        </view>
    </eui-popup>
</template>

<script setup type="ts">
import { ref, reactive, onMounted } from 'vue';
import dayjs from 'dayjs';
import service from '@/common/service';
import { getRelatedName, getDictList, getDictName, getUserDictList } from '../components/RelatedName.js';
import { getRdsSysConfig } from '@/hooks/init';
import {
    calcAtInByPt,
    calculatePackages,
    calcPtInByPtPay,
    validateOddLot,
    calcPetpayByPtPay,
    round,
} from '@/hooks/useCalculateMethod';
import { dateDiff, dateAdd, todayAdd, isDomesticBarcode } from '@/hooks/useUtils';
import { mapState, mapMutations } from 'vuex';
import { rdsRequest, getRdsUrl, rdsRequestAsync } from '@/hooks/rdsServices';
import { onLoad } from "@dcloudio/uni-app";
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";
import { set } from "vue-demi";
import { useWeightUnits } from '@/hooks/useWeightUnits'


const mainStore = useMainStore();
const { loginInfo } = mainStore;
const { weightUnits } = useWeightUnits();
const rdsUrl = getRdsUrl();

const gdsPopup = ref(null);
const euiNavBar = ref(null);
const RdsSearchBar = ref(null);
const cardNPackInput = ref(null);
const cardNOddInput = ref(null);
const cardNIptInput = ref(null);
const cardRecNInput = ref(null);
const cardNFreeInput = ref(null);
const serialNoInput = ref(null);

const sUserStore = ref('');

const c_sku_rec_total = ref(0);
const c_n_rec_total = ref(0);
const c_n_rec_free_total = ref(0);

const c_order_sku = ref(0);
const c_order_n_total = ref(0);
const c_order_n_free_total = ref(0);

const title = ref('我要收货');
const isModified = ref(false);
// const c_po_id = ref('');//订单号
const c_gcode = ref('');
const height = ref(0);
const showDiff = ref(false);
const c_disabled = ref(false);
const c_status = ref('0');
const searchText = ref('');
const isOpened = ref('none');
const options = ref([
    {
        text: '删除',
        style: {
            backgroundColor: '#F56C6C',
        }
    },
]);
const sysConfig = ref({
    policyD: '',//永续订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    policyN: '',//无订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    policyO: '',//正常订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    policyP: '',//促销订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    policyC: '',//变价订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    ptInMinTimes: 0,//验收进价异常下限倍数
    ptInMaxTimes: 0,//验收进价异常上限倍数
    isMustInputPdt: '',//有保质期商品是否必须录入生产日期；0-否；1-是
    minExpiredPercent: 0,//允许收货的留存时间占保质期的最低百分比
    exceedOutDate: 0,//保质期报警天数,生产日期+保质期距当前日期天数大于保质期报警天数则报警
    mustInputPdtExceptAdnos: [],//必须录入生产日期的例外部门
    recOverOrderRate: 0,//验收数量最多可超过订货数量比例
    productDateCtrl: 0,//是否开启生产日期控制
    canOverOrderClass: [],//验收数量可超过订货数量的品类
    inputType: '1' // 1-件数零数分别录入方式 2-自动识别含量单值录入方式
});
const currentGds = ref({});
const mainData = ref({
    c_status: '0',
    c_approve_status: '1'
});
const serialNo = ref('');

const detailData = ref([]);
const listManager = ref([]);
const diffListManager = ref([]);

const recNewList = ref([]);
onLoad(async (option) => {
    sUserStore.value = option.storeId;
    mainData.value.c_id = option.c_id;
    c_gcode.value = option.c_gcode;
    if (option.c_id) {
        service.enjoyShowLoading('正在加载...');
        await billQuery();
        await billQueryMiddle("0");
        service.enjoyHideLoading();
    } else if (option.c_po_id) {
        await GetRecBillList();
    }
    await getSysConfig();
});
const getSysConfig = async () => {
    sysConfig.value.policyD = await getRdsSysConfig("商品验收控制参数", "永续订单验收进价控制策略");
    sysConfig.value.policyN = await getRdsSysConfig("商品验收控制参数", "无订单验收进价控制策略");
    sysConfig.value.policyO = await getRdsSysConfig("商品验收控制参数", "正常订单验收进价控制策略");
    sysConfig.value.policyP = await getRdsSysConfig("商品验收控制参数", "促销订单验收进价控制策略");
    sysConfig.value.policyC = await getRdsSysConfig("商品验收控制参数", "变价订单验收进价控制策略");
    sysConfig.value.ptInMinTimes = Number(await getRdsSysConfig("商品验收控制参数", "验收进价异常下限倍数"));
    sysConfig.value.ptInMaxTimes = Number(await getRdsSysConfig("商品验收控制参数", "验收进价异常上限倍数"));
    sysConfig.value.isMustInputPdt = await getRdsSysConfig("商品验收控制参数", "有保质期商品是否必须录入生产日期");
    sysConfig.value.minExpiredPercent = Number(await getRdsSysConfig("商品验收控制参数", "允许收货留存时间占保质期的最低百分比"));
    sysConfig.value.exceedOutDate = Number(await getRdsSysConfig("商品验收控制参数", "保质期报警天数"));
    sysConfig.value.mustInputPdtExceptAdnos = await getDictList("有保质期商品是否必须录入生产日期的例外部门");
    sysConfig.value.recOverOrderRate = Number(await getRdsSysConfig("商品验收控制参数", "验收数量最多可超过订货数量比例"));
    sysConfig.value.productDateCtrl = await getRdsSysConfig("商品验收控制参数", "是否开启生产日期控制");
    sysConfig.value.canOverOrderClass = await getUserDictList("验收数量可超过订货数量的品类");
    sysConfig.value.inputType = await getRdsSysConfig("供应链管理参数", "商品件数零数录入方式") || '1';
};

const searchConfirm = async (e) => {
    searchText.value = e.value;
    try {
        //验证批号规则
        const serialInfo = await valiSerialNoRule();

        let barCode = '';
        if (searchText.value.length === 7) {
            const gdsInfo = await getGdsInfo(searchText.value);
            barCode = gdsInfo.c_barcode;
        } else {
            barCode = searchText.value;
        }
        //c_id为空时，扫描商品
        if (!mainData.value.c_id) {
            service.enjoyShowLoading('正在加载...');
            await billListByGCode(barCode);
            await billQuery();
            await billQueryMiddle('0');
            let item = listManager.value.find(x => x.c_barcode === barCode);
            if (!item) {
                item = detailData.value.find(x => x.c_barcode === barCode);
            }
            await onClickGdsInfo({
                ...item,
                c_serial_no: serialInfo?.serialNo,
                c_product_dt: serialInfo?.sda,
                c_expect_dt: serialInfo?.eda,
            })
            service.enjoyHideLoading();
            return;
        }

        let item = listManager.value.find(x => x.c_barcode === barCode && x.c_serial_no === serialInfo?.serialNo);
        if (!item) {
            item = listManager.value.find(x => x.c_barcode === barCode);
        }
        if (!item) {
            item = detailData.value.find(x => x.c_barcode === barCode && x.c_serial_no === serialInfo?.serialNo);
        }
        if (!item) {
            item = detailData.value.find(x => x.c_barcode === barCode);
        }
        if (item) {
            await onClickGdsInfo({
                ...item,
                c_serial_no: serialInfo?.serialNo,
                c_product_dt: serialInfo?.sda,
                c_expect_dt: serialInfo?.eda,
            })
            return;
        }
        // 调用服务验证商品是否存在
        // 多包装条码
        const req = {
            IuputData: searchText.value
        }
        const packResult = await rdsRequestAsync(rdsUrl.scApi, 'Rds公共服务', 'GetGdsPack', req, '701');
        if (packResult.HasException) {
            const newGds = detailData.value.find(x => x.c_barcode === barCode);
            if (!newGds) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: packResult.Exception.Message,
                    mask: true,
                });
                RdsSearchBar.value.clear();
                return;
            }
            await onClickGdsInfo({
                ...newGds,
            })
            return;
        }
        item = listManager.value.find(x => x.c_gcode === packResult.ObjectData.c_gcode);
        if (item) {
            await onClickGdsInfo({ ...item, c_note: searchText.value })
            return;
        } else {
            item = detailData.value.find(x => x.c_gcode === packResult.ObjectData.c_gcode);
            if (item) {
                const flag = await enjoyConfirm(`商品条码[${searchText.value}]存在条码变更，是否使用商品[${item.c_gcode}]？`);
                if (!flag) {
                    return;
                }
                await onClickGdsInfo({ ...item, c_note: searchText.value })
                return;
            }
            //根据条码查询编码
            const gdsInfo = await getGdsInfo(barCode);
            const gCode = gdsInfo.c_gcode;
            item = detailData.value.find(x => x.c_gcode === gCode);
            if (item) {
                const flag = await enjoyConfirm(`商品条码[${searchText.value}]存在条码变更，是否使用商品[${gCode}]？`);
                if (!flag) {
                    return;
                }
                await onClickGdsInfo({ ...item, c_note: searchText.value })
                return;
            }
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: `单据不存在此商品[${searchText.value}]！`,
                mask: true,
            });
            RdsSearchBar.value.clear();
        }
    } catch (error) {
        service.enjoyHideLoading();
        console.error(error);
    }
};

/**
 * 验证批号规则
 */
const valiSerialNoRule = async () => {
    const serialInfo = {
        gcode: searchText.value,
        serialNo: '',
        sda: null,
        eda: null
    };
    const req = {
        storeId: sUserStore.value,
        serialNo: searchText.value
    };
    const valSerialRes = await rdsRequestAsync(rdsUrl.scApi, "Rds公共服务", "ValiSerialNoRule", req);
    if (valSerialRes.HasException) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: valSerialRes.Exception.Message,
            mask: true,
        });
        return null;
    } else {
        if (valSerialRes.ObjectData?.isMatchRule) {
            serialNo.value = searchText.value;
            serialInfo.gcode = valSerialRes.ObjectData.gcode;
            serialInfo.serialNo = searchText.value;
            serialInfo.sda = valSerialRes.ObjectData.sda;
            serialInfo.eda = valSerialRes.ObjectData.eda;
            searchText.value = valSerialRes.ObjectData.gcode;
            return serialInfo;
        }
    }
    return null;

};

const clear = (e) => {
    switch (e) {
        case 'c_n':
            currentGds.value.c_n = 0;
            break;
        case 'c_product_dt':
            currentGds.value.c_product_dt = null;
            break;
        case 'c_expired_dt':
            currentGds.value.c_expired_dt = null;
            break;

    }
}
const getPtPolicy = async () => {
    let ptPolicy = ''
    const priceType = mainData.value?.c_src_type?.startsWith('5F') ? 'D' : mainData.value?.c_price_type
    //0-正常订单、1-首单折扣订单、2-可变价订单、3-促销订单、9-无订单
    switch (priceType) {
        case '0':
        case '1':
            ptPolicy = sysConfig.value.policyO;
            break;
        case '2':
            ptPolicy = sysConfig.value.policyC;
            break;
        case '3':
            ptPolicy = sysConfig.value.policyP;
            break;
        case '9':
            ptPolicy = sysConfig.value.policyN;
            break;
        case 'D':
            ptPolicy = sysConfig.value.policyD;
            break;
        default:
            ptPolicy = sysConfig.value.policyO;
            break;
    }
    if (ptPolicy === '0') {
        c_disabled.value = true;
    }
    return ptPolicy;
};
const getGdsInfo = async (gcode) => {
    const req = {
        WhereList: [
            { c_col: "c_store_id", c_oper: "等于", c_value: mainData.value.c_store_id, c_logic: "而且" },
            { c_col: "inputOrigMode", c_logic: "而且", c_value: "1", c_oper: "等于" },
            { c_col: "c_gcode", c_oper: "等于", c_value: gcode, c_logic: "而且" }
        ]
    };
    const result = await rdsRequest(rdsUrl.bcApi, '弹窗通用查询', 'FetchComplexGds', req);
    if (result.ReturnObject.length > 0) {
        console.log("result", result)
        return result.ReturnObject[0]
    }
    return gcode;
};
// 选择框点击事件
const clickRight = async (type, elemId) => {
    console.log("type", type)
    selectType.value = type;
    if (type === 'c_store_id') {
        await uni.navigateTo({
            url: '../modals/store/index'
        });
    } else if (type === 'c_po_id') {
        if (!sUserStore.value) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '请先选择机构'
            });
            return false;
        }
        // 选择订单
        await uni.navigateTo({
            url: '../modals/recOrder/index?storeId=' + sUserStore.value
        });
    } else if (type === 'c_store_id_name') {
        await uni.navigateTo({
            url: '../modals/store/index'
        });
    }
};
const onClickGdsInfo = async (item, index) => {
    console.log("item, index", item, index)
    if (!item.c_gcode) {
        return;
    }
    let currentItem = listManager.value.find(x => x.c_gcode === item.c_gcode && x.c_barcode === item.c_barcode && x.c_serial_no === item.c_serial_no);
    if (!currentItem) {
        currentItem = listManager.value.find(x => x.c_gcode === item.c_gcode && x.c_barcode === item.c_barcode);
    }
    currentGds.value = {
        ...item,
        c_n: !currentItem ? 0 : currentItem.c_n,
        c_n_free: !currentItem ? 0 : currentItem.c_n_free,
        c_n_pack: !currentItem ? 0 : currentItem.c_n_pack,
        c_n_odd: !currentItem ? 0 : currentItem.c_n_odd,
    };
    gdsPopup.value.open('bottom');
    // const isDomestic = isDomesticBarcode(currentGds.value.c_barcode);
    // if (isDomestic) {
    //     c_disabled = true
    //     // $refs.productDtRef.getFocus();
    // } else {
    //     c_disabled = false
    //     // $refs.expiredDtRef.getFocus();
    // }

};
// 扫码
const clickScanRight = async (type) => {
    if (type === "c_gcode") {
        await uni.scanCode({
            success: async function (res) {
                if (res.result) {
                    c_gcode.value = res.result;
                    searchText.value = res.result;
                    await searchConfirm(res.result);
                }
            }
        });
    }
};
const SelectionChanged = async (event) => {
    console.log("event", event, event.type)
    if (event.type === 'c_store_id') {
        sUserStore.value = event.c_store_id;
    } else if (event.type === 'c_id') {
        mainData.value.c_id = event.c_id;
        service.enjoyShowLoading('正在加载...');
        await billQuery();
        await billQueryMiddle('0');
        service.enjoyHideLoading();
    }
};
const validateDetail = async (args) => {
    console.log("args", args)
    const { type, fieldName, oldValue, newValue, itemIndex } = args;
    let result = null;
    let overResult = null;
    let validateWeightUnitsResult = null;
    let c_n;
    let validateResult;
    switch (fieldName) {
        case 'c_pt_pay':
            const pt_pay = newValue;
            //0-不可更改，1-可改低，2-可任意修改
            const ptPolicy = await getPtPolicy();
            if (ptPolicy === '0') {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '当前结算价不允许调整'
                });
                setTimeout(() => {
                    currentGds.value.c_pt_pay = oldValue;
                    cardPtPayInput.value.inputValue = oldValue;
                }, 300);
                break;
            } else if (ptPolicy === '1' && newValue > currentGds.value.c_pt_pay) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '结算价不允许调高'
                });
                setTimeout(() => {
                    currentGds.value.c_pt_pay = oldValue;
                    cardPtPayInput.value.inputValue = oldValue;
                    cardPtPayInput.value.getFocus()
                }, 300);
                break;
            }
            if (sysConfig.value.ptInMaxTimes !== 0) {
                if (pt_pay > currentGds.value.c_pt_pay_con * sysConfig.value.ptInMaxTimes) {
                    await uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: `当前结算价与合同结算价相比，超出上限倍数[${sysConfig.value.ptInMaxTimes}]的限制！`
                    });
                    setTimeout(() => {
                        currentGds.value.c_pt_pay = oldValue;
                        cardPtPayInput.value.inputValue = oldValue;
                        cardPtPayInput.value.getFocus()
                    }, 300);
                    break;
                }
            }
            if (sysConfig.value.ptInMinTimes !== 0) {
                if (pt_pay < currentGds.value.c_pt_pay_con / sysConfig.value.ptInMinTimes) {
                    await uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: `当前结算价与合同结算价[${currentGds.value.c_pt_pay_con}]相比，低于下限倍数[${sysConfig.value.ptInMinTimes}]的限制！`
                    });
                    setTimeout(() => {
                        cardPtPayInput.value.getFocus()
                    }, 300);
                    break;
                }
            }
            currentGds.value.c_pt_pay = pt_pay
            currentGds.value.c_pt_in = calcPtInByPtPay(
                {
                    c_pt_pay: pt_pay,
                    c_tax_rate: currentGds.value.c_tax_rate,
                    c_tax_rate_pay: currentGds.value.c_tax_rate_pay,
                    c_tax_src: currentGds.value.c_tax_src
                })

            currentGds.value.c_pet_pay = calcPetpayByPtPay({
                c_pt_pay: pt_pay,
                c_tax_rate_pay: currentGds.value.c_tax_rate_pay,
                c_tax_src: currentGds.value.c_tax_src
            });
            await calcRowAmount();
            break;
        case 'c_n_pack':
            if (newValue < 0 || newValue > 999999) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '请输入0~999999的数！'
                });
                currentGds.value.c_n_pack = 0;
                setTimeout(() => {
                    cardNPackInput.value.getFocus()
                }, 300);
                return
            }
            currentGds.value.c_n_pack = parseInt(newValue);
            c_n = currentGds.value.c_n_pack * currentGds.value.c_order_pack + currentGds.value.c_n_odd;
            currentGds.value.c_n_input = round(c_n / currentGds.value.c_order_pack, 3);
            currentGds.value.c_n = c_n;
            overResult = await canOverOrderValidate(currentGds.value.c_ccode, currentGds.value.c_n_confirm, c_n,)
            if (!overResult) {
                // currentGds.value.c_n_pack = oldValue;
                // cardNPackInput.value.inputValue = oldValue;
                setTimeout(() => {
                    cardNPackInput.value.getFocus()
                }, 300);
                return
            }
            await calcRowAmount(currentGds.value);
            break;
        case 'c_n_odd':
            if (newValue < 0 || newValue > 999999) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '请输入0~999999的数！'
                });
                currentGds.value.c_n_odd = 0;
                setTimeout(() => {
                    cardNOddInput.value.getFocus()
                }, 300);
                return
            }
            currentGds.value.c_n_odd = newValue;
            validateWeightUnitsResult = await validateWeightUnits(newValue);
            if (!validateWeightUnitsResult) {
                setTimeout(() => {
                    cardNOddInput.value.getFocus()
                }, 300);
                return;
            }
            validateResult = validateOddLot(newValue, currentGds.value.c_n_pack, currentGds.value.c_order_pack, '1');
            result = validateResult.result;
            if (!result || result?.validated) {
                currentGds.value.c_n = validateResult.n;
                currentGds.value.c_n_pack = validateResult.npack;
                currentGds.value.c_n_input = round(currentGds.value.c_n / currentGds.value.c_order_pack, 3);
                if (validateResult.result) {
                    currentGds.value.c_n_odd = validateResult.result?.retValue;
                }
                overResult = await canOverOrderValidate(currentGds.value.c_ccode, currentGds.value.c_n_confirm, validateResult.n,)
                if (!overResult) {
                    // currentGds.value.c_n_odd = 0;
                    // cardNOddInput.value.inputValue = oldValue;
                    setTimeout(() => {
                        cardNOddInput.value.getFocus()
                    }, 300);
                    return
                }

                await calcRowAmount(currentGds.value);
            } else {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: result?.message
                });
                // currentGds.value.c_n_odd = oldValue;
                // cardNOddInput.value.inputValue = oldValue;
                setTimeout(() => {
                    cardNOddInput.value.getFocus()
                }, 300);
            }
            break;
        case 'c_n_input':
            if (newValue < 0 || newValue > 999999) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '请输入0~999999的数！'
                });
                currentGds.value.c_n_input = 0;
                setTimeout(() => {
                    cardNIptInput.value.getFocus()
                }, 300);
                return;
            }

            const c_n_odd = round(newValue * currentGds.value.c_order_pack, 3);
            validateResult = validateOddLot(c_n_odd, currentGds.value.c_n_pack, currentGds.value.c_order_pack, '1', true);
            result = validateResult.result;
            if (!result || result?.validated) {
                validateWeightUnitsResult = await validateWeightUnits(result?.retValue);
                if (!validateWeightUnitsResult) {
                    setTimeout(() => {
                        cardNIptInput.value.getFocus()
                    }, 300);
                    return;
                }
                currentGds.value.c_n = validateResult.n;
                currentGds.value.c_n_pack = validateResult.npack;
                currentGds.value.c_n_input = newValue;
                if (result) {
                    currentGds.value.c_n_odd = result.retValue;
                }
                overResult = await canOverOrderValidate(currentGds.value.c_ccode, currentGds.value.c_n_confirm, validateResult.n,)
                if (!overResult) {
                    setTimeout(() => {
                        cardNIptInput.value.getFocus()
                    }, 300);
                    return
                }
                await calcRowAmount(currentGds.value);
            } else {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: result?.message
                });
                setTimeout(() => {
                    cardNIptInput.value.getFocus()
                }, 300);
            }
            break;
        case 'c_n':
            if (newValue === oldValue) {
                return;
            }
            const recN = newValue;
            currentGds.value.c_n = recN;
            validateWeightUnitsResult = await validateWeightUnits(newValue);
            if (!validateWeightUnitsResult) {
                // currentGds.value.c_n = oldValue;
                // cardRecNInput.value.inputValue = oldValue;
                setTimeout(() => {
                    cardRecNInput.value.getFocus()
                }, 300);
                return;
            }
            overResult = await canOverOrderValidate(currentGds.value.c_ccode, currentGds.value.c_n_confirm, recN,)
            if (!overResult) {
                // currentGds.value.c_n = oldValue;
                // cardRecNInput.value.inputValue = oldValue;
                cardRecNInput.value.getFocus();
                return
            }
            result = await calculatePackages(currentGds.value.c_order_pack, recN);
            currentGds.value.c_n_pack = result.npack;
            currentGds.value.c_n_odd = result.odd;
            currentGds.value.c_n_input = round(newValue / currentGds.value.c_order_pack, 3);
            await calcRowAmount();
            break;
        case 'c_n_free':
            const recFreeN = newValue;
            currentGds.value.c_n_free = recFreeN;
            await calcRowAmount();
            break;
        case 'c_serial_no':
            if (newValue) {
                // 验证录入的批号
                const req = {
                    storeId: sUserStore.value,
                    gcode: currentGds.value.c_gcode,
                    serialNo: newValue
                };
                const valSerialRes1 = await rdsRequestAsync(rdsUrl.scApi, "Rds公共服务", "ValiSerialNoRule", req);
                if (valSerialRes1.HasException) {
                    return {
                        validated: false,
                        message: valSerialRes1.Exception.Message
                    }
                }
                if (valSerialRes1.ObjectData && valSerialRes1.ObjectData.isMatchRule) {
                    // 验证生产日期和截止日期
                    if (valSerialRes1.ObjectData.sda || valSerialRes1.ObjectData.eda) {
                        let productDt = valSerialRes1.ObjectData.sda;
                        if ((currentGds.value.c_od_day ?? 0) > 0) {
                            if (valSerialRes1.ObjectData.eda) {
                                productDt = dateAdd((currentGds.value.c_od_day) * -1, valSerialRes1.ObjectData.eda, converOdUnit(currentGds.value.c_od_unit));
                            }
                        }
                        // 验证 收货日期
                        if (mainData.value.c_rec_dt) {
                            if (productDt && dayjs(mainData.value.c_rec_dt).format('YYYY-MM-DD') < dayjs(productDt).format('YYYY-MM-DD')) {
                                return {
                                    validated: false,
                                    message: `生产日期[${dayjs(productDt).format('YYYY-MM-DD')}]不可晚于收货日期[${dayjs(mainData.value.c_rec_dt).format('YYYY-MM-DD')}]！`
                                }
                            }
                        }
                        if (productDt && dayjs(productDt).format('YYYY-MM-DD') > formatNow('YYYY-MM-DD')) {
                            return {
                                validated: false,
                                message: `生产日期[${dayjs(productDt).format('YYYY-MM-DD')}]不可晚于今天！`
                            }
                        }
                        if ((currentGds.value.c_od_day ?? 0) > 0) {
                            result = await validateProductDt(currentGds.value, productDt);
                        }
                        else {
                            currentGds.value.c_expired_dt = valSerialRes1.ObjectData.eda;
                            currentGds.value.c_product_dt = valSerialRes1.ObjectData.sda;
                        }
                    }
                }
            }
            break;
    }
};
const buttonClick = async (e) => {
    const { singleTag, modelValue, type } = e;
    switch (singleTag) {
        case 'showDiff':
            diffListManager.value = [...listManager.value.filter(item => item.c_n_confirm !== item.c_n && item.c_n !== 0)];
            showDiff.value = !showDiff.value;
            break;
        case 'submit':
            // 提交
            if (!mainData.value.c_po_id) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '订单号不能为空！'
                });
                return false;
            }

            if (!listManager.value.length > 0) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '验收商品不能为空！'
                });
                return false;
            }
            //生产日期不能为空
            // const filterList = detailData.value.filter(item => item.c_product_dt === '' || item.c_product_dt === null);
            // const gcodes = filterList.map(item => item.c_gcode);
            // if (gcodes.length > 0) {
            //     await uni.showToast({
            //         icon: 'none',
            //         title: `商品${gcodes}生产日期不能为空！请检查`,
            //     });
            //     return false;
            // }

            //验证保持和rds一致，先注释
            // const result = validateBarcode();
            // if (!result) {
            //     return false;
            // }


            await uni.showModal({
                title: ' 提示',
                content: '请确认，提交验收的商品?',
                showCancel: true,
                success: async (res) => {
                    if (res.confirm) {
                        service.enjoyShowLoading('正在提交...');
                        await saveBill({ newItem: recNewList.value });
                        const result = await submitBill();
                        if (result) {
                            await billQueryMiddle('0');
                            await billQuery();
                        }
                        service.enjoyHideLoading();
                        currentGds.value = {};
                        recNewList.value = [];
                    }
                }
            });
            break;
        case 'detail':
            await uni.navigateTo({
                url: './detail?c_id=' + mainData.value.c_id + '&storeId=' + mainData.value.c_store_id
            });
            break
        case 'cancel':
            gdsPopup.value.close()
            RdsSearchBar.value.clear();
            break;
        case 'submit3':
            // if (c_disabled) {
            //     if (!validateProductDt(currentGds.value.c_product_dt)) {
            //         return;
            //     }
            // } else {
            //     if (!validateExpiredDt(currentGds.value.c_expired_dt)) {
            //         return;
            //     }
            // }
            if (sysConfig.value.isMustInputPdt === '1' &&//参数：有保质期商品是否必须录入生产日期
                currentGds.value.c_od_day > 0 &&//保质期大于0
                !currentGds.value.c_product_dt &&//生产日期为空
                // (currentGds.value.c_n_free > 0 || //赠品收获数量
                //     currentGds.value.c_n > 0) &&//收货数量
                !sysConfig.value.mustInputPdtExceptAdnos.some(adno => currentGds.value.c_adno.startsWith(adno.value)) //排除例外部门的
            ) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '商品有保质期管理，请录入生产日期'
                });
                return;
            }

            // 验证 生产日期是否早于历史验收的生产日期
            if (sysConfig.value.productDateCtrl == '1' || sysConfig.value.productDateCtrl == '2') {
                // 供应商、商品、生产日期
                const rep = await rdsRequestAsync(rdsUrl.scApi, '商品验收单', 'QueryRecGaByCodePrv', { gcode: currentGds.value.c_gcode, provider: mainData.value.c_provider }, 'S01');
                if (rep.HasException) {
                    await uni.showToast({
                        duration: 2500,
                        icon: 'none',
                        title: rep.Exception.Message
                    });
                    return;
                }
                if (rep.ObjectData && rep.ObjectData?.c_product_dt && currentGds.value.c_product_dt < dayjs(rep.ObjectData?.c_product_dt).format('YYYY-MM-DD')) {
                    await uni.showToast({
                        duration: 2500,
                        icon: 'none',
                        title: `商品生产日期[${dayjs(currentGds.value.c_product_dt).format('YYYY-MM-DD')}]早于本商品在验收单[${rep.ObjectData.c_id}]的生产日期[${dayjs(rep.ObjectData?.c_product_dt).format('YYYY-MM-DD')}]!`
                    });
                    if (sysConfig.value.productDateCtrl === '2') {
                        return;
                    }
                }
            }

            // const errGds = listManager.value.filter(a => ['2', '1'].includes(a.c_sn_method) && !a.c_serial_no).map(a => a.c_gcode);
            // if (errGds.length) {
            //     await uni.showToast({
            //         duration: 2500,
            //         icon: 'none',
            //         title: `商品${errGds.join(',')}在机构[${listManager.value.c_store_id}]的系列号管理方式不为【否】，请为商品录入批号/SN！`
            //     });
            //     return;
            // }
            const result = await validateGdsStore(currentGds.value);
            if (['2', '1'].includes(result.c_sn_method) && !currentGds.value.c_serial_no) {
                await uni.showToast({
                    duration: 2500,
                    icon: 'none',
                    title: `商品${currentGds.value.c_gcode}在机构[${sUserStore.value}]的系列号管理方式不为【否】，请为商品录入批号/SN！`
                });
                serialNoInput.value.getFocus();
                return;
            }

            if (currentGds.value.c_n_free > 0 && currentGds.value.c_n === 0) {
                const flag = await enjoyConfirm("当前录入为赠品数量，是否确认？");
                if (!flag) {
                    return;
                }
            }

            service.enjoyShowLoading("正在加载...");
            try {
                const result = await saveValidate(currentGds.value);
                if (!result.Result) {
                    await uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: result.Error.Message
                    });
                    return;
                }


                const submittedList = await billQueryMiddleSubmitted();
                const middleList = [...submittedList, ...listManager.value];

                //多批号的情况下，需要新增验收单
                //判断是否新批号商品
                let isNewSerialNo = false;
                const gsort = detailData.value.length + recNewList.value.length + 1;

                const middleFilter = middleList.filter(item => item.c_gcode === currentGds.value.c_gcode && item.c_barcode === currentGds.value.c_barcode);
                if (middleFilter.length > 0) {
                    const middleItem = middleFilter.find(item => item.c_serial_no == currentGds.value.c_serial_no);
                    if (!middleItem) {
                        isNewSerialNo = true;
                        recNewList.value.push({
                            ...currentGds.value,
                            c_gsort: gsort,
                            c_n: 0,
                            c_n_free: 0,
                            c_n_pack: 0,
                            c_n_odd: 0,
                        });
                    }
                }
                // if (middleFilter.length > 0) {
                //     isNewSerialNo = true;
                //     recNewList.value.push({
                //         ...currentGds.value,
                //         c_gsort: gsort,
                //         c_n: 0,
                //         c_n_free: 0,
                //         c_n_pack: 0,
                //         c_n_odd: 0,
                //     });
                // }

                let item = listManager.value.find(item => item.c_gcode === currentGds.value.c_gcode && item.c_barcode === currentGds.value.c_barcode && item.c_serial_no === currentGds.value.c_serial_no);
                if (!item) {
                    if (isNewSerialNo) {
                        await saveBillMiddle({ newItem: { ...currentGds.value, c_gsort: gsort } });
                        isNewSerialNo = false;
                    } else {
                        await saveBillMiddle({ newItem: currentGds.value });
                    }
                } else {
                    await saveBillMiddle({
                        modifiedItem: currentGds.value,
                    });
                }

                await billQueryMiddle('0');
                // $set(detailData.value, currentGdsIndex, currentGds.value)
                gdsPopup.value.close();
                await calcMainAmount();
                service.enjoyHideLoading();
                RdsSearchBar.value.clear();
                // diffListManager.value = detailData.value.filter(item => item.c_n_confirm !== item.c_n && item.c_n !== 0);
                isModified.value = true;
            } catch (error) {
                console.log("error", error)
                service.enjoyHideLoading();
            }

            break;
    }
};
// 获取单据列表信息
const GetRecBillList = async () => {
    service.enjoyShowLoading('正在查询...');
    const req = {
        WhereList: [
            mainData.value.c_id ? { c_col: "c_id", c_oper: "等于", c_value: mainData.value.c_id, c_logic: "而且" } : {},
            { c_col: "c_store_id", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" },
            { c_col: "c_status", c_oper: "等于", c_value: '0', c_logic: "而且" },
            { c_col: "c_po_type", c_oper: "等于", c_value: '521', c_logic: "而且" }
        ]
    };
    if (mainData.value.c_po_id) {
        req.WhereList.push(
            { c_col: "c_po_id", c_oper: "等于", c_value: mainData.value.c_po_id, c_logic: "而且" }
        )
    }
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyQueryList', req, '701');
    service.enjoyHideLoading();
    const _data = result.ReturnObject;
    if (_data.length === 1) {
        mainData.value = _data[0];
        await billQuery();
    } else if (_data.length > 1) {
        await uni.navigateTo({
            url: '../modals/recOrder/index?storeId=' + sUserStore.value + "&orderData=" + JSON.stringify(_data)
        })
    } else {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '未查询到单据',
            mask: true,
        });
        mainData.value = {};
        detailData.value = [];
    }
};
// 获取订货单单据列表信息
const billListByGCode = async (barCode) => {
    const req = {
        WhereList: [
            { c_col: "c_store_id", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" },
            { c_col: "c_status", c_oper: "等于", c_value: '0', c_logic: "而且" },
            { c_col: "c_approve_status", c_oper: "等于", c_value: '1', c_logic: "而且" },
            { c_col: "c_po_type", c_oper: "等于", c_value: '521', c_logic: "而且" },
            { c_col: "c_src_id", c_oper: "不为空", c_value: '', c_logic: "而且" },
        ]
    };
    if (barCode) {
        req.WhereList.push({
            c_col: "c_gcode",
            c_oper: "等于",
            c_value: barCode,
            c_logic: "而且",
        });
    }
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyQueryList', req, '701');
    var _data = result.ReturnObject;
    if (_data.length === 1) {
        mainData.value = _data[0];
        return true;
    } else if (_data.length > 1) {
        await uni.navigateTo({
            url: '../modals/recOrder/index?storeId=' + sUserStore.value + "&orderData=" + JSON.stringify(_data)
        });
        return true;
    } else {

        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: `商品[${searchText.value}]不存在!`,
            mask: true,
        });
        setTimeout(() => {
            RdsSearchBar.value.clear();
        }, 300);
        return false;
    }
};
// 获取单据详情信息
const billQuery = async () => {
    if (!mainData.value.c_id) {
        return;
    }
    const req = {
        BillId: mainData.value.c_id,
    };
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyBillQuery', req, '701');
    if (result.ds.length > 0) {
        mainData.value = result.ds[0];
        detailData.value = result.ds1;
        title.value = mainData.value.c_po_id;
        setTimeout(() => {
            RdsSearchBar.value.clear();
        }, 300);
        c_order_sku.value = result.ds1.length || 0;
        c_order_n_total.value = result.ds1.reduce((pre, current) => pre + (current.c_n_confirm), 0);
        c_order_n_free_total.value = result.ds1.reduce((pre, current) => pre + (current.c_n_free_confirm), 0);
    } else {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '未查询到数据',
            mask: true,
        });
    }
};
const billQueryMiddle = async (submitStatus) => {
    if (!mainData.value.c_id) {
        return;
    }
    const req = {
        c_id: mainData.value.c_id,
        c_submit_status: submitStatus
        // BillId: mainData.value.c_id,
        // Sql:{ WhereList : [
        //     {c_col: "c_mk_userno", c_oper: "等于", c_value: loginInfo.sUser, c_logic: "而且"},
        //     {c_col: "c_submit_status", c_oper: "等于", c_value: submitStatus, c_logic: "而且"}
        // ]}
    };
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单中间表', 'EnjoyBillQueryMiddle', req, '701');
    if (result.ds.length > 0) {
        listManager.value = result.ds1;
        c_sku_rec_total.value = result.ds1.reduce((pre, current) => pre + (current.c_n > 0 || current.c_n_free > 0), 0);
        c_n_rec_total.value = result.ds1.reduce((pre, current) => pre + (current.c_n ?? 0), 0);
        c_n_rec_free_total.value = result.ds1.reduce((pre, current) => pre + (current.c_n_free ?? 0), 0);
        setTimeout(() => {
            RdsSearchBar.value.clear();
        }, 300);
    } else {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '未查询到数据',
            mask: true,
        });
    }
};

const billQueryMiddleSubmitted = async () => {
    if (!mainData.value.c_id) {
        return;
    }
    const req = {
        c_id: mainData.value.c_id,
        c_submit_status: '1'
    };
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单中间表', 'EnjoyBillQueryMiddle', req, '701');
    return result.ds;
};

const validateWeightUnits = async (recN) => {
    if (!weightUnits.value.includes(currentGds.value.c_order_unit)) {
        if (recN % 1 > 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '本商品验收数量不允许录入小数，仅重量单位商品可以录入小数'
            });
            return false;
        }
    }
    return true;
};
const validateBarcode = async () => {
    let productDtGds = [];
    let excludeDtGds = [];
    let warnMessage = '';
    detailData.value.forEach((x, index) => {
        const isDomestic = isDomesticBarcode(x.c_barcode);
        if (isDomestic) {//国内码
            if (!x.c_product_dt) {
                productDtGds.push(index + 1)
            }
        } else {//国外码
            if (!x.c_expired_dt) {
                excludeDtGds.push(index + 1)
            }
        }
    })
    if (productDtGds.length > 0) {
        warnMessage += `商品第${productDtGds.join(',')}行未录入生产日期`;
    }
    if (excludeDtGds.length > 0) {
        warnMessage += `商品第${excludeDtGds.join(',')}行未录入限用日期`;
    }
    if (warnMessage !== '') {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: warnMessage
        });
        return false;
    }
    return true;
};
// 保存数据
const saveBill = async ({ newItem: newItem, modifiedItem: modifiedItem, delItem: delItem }) => {
    //验证生产日期
    const validateResult = await validateProduceDt()
    if (!validateResult.validated) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: validateResult.msg
        });
        return false;
    }
    const req = {
        NewList: [],
        ModifiedList: [mainData.value],
        DelList: [],
        TableName: "tb_io_rec",
        PrimaryKeys: ["c_tenant_id", "c_id"],
        ChildData: [{
            ChildTableName: "tb_io_rec_g",
            ParentTableName: "tb_io_rec",
            ChildColumnNames: ["c_id"],
            ParentColumnNames: ["c_id"],
            ChildSaveModel: {
                NewList: newItem ? newItem : [],
                ModifiedList: modifiedItem ? [modifiedItem] : [],
                DelList: delItem ? [delItem] : [],
                TableName: "tb_io_rec_g",
                PrimaryKeys: ["c_tenant_id", "c_id", "c_gsort"],
            }
        }],
        BillSet: {
            BillIdKeyValue: {
                key: "c_id",
                value: mainData.value.c_id
            },
            BillVariable: "",
            TableName: "tb_io_rec",
            BillName: "商品验收单"
        },
        TimeOut: 600
    };
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyBillSaveNew', req, '701');
    console.log("result", result)
    await uni.showToast({
        duration: 2000,
        icon: 'none',
        title: `保存成功`
    });
    isModified.value = false;
    return true;
};

const saveValidate = async (param) => {
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单中间表', 'EnjoyBillSaveBeforeValidate', param, '701');
    return result;
};
const saveBillMiddle = async ({ newItem: newItem, modifiedItem: modifiedItem, delItem: delItem }) => {
    //验证生产日期
    const validateResult = await validateProduceDt()
    if (!validateResult.validated) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: validateResult.msg
        });
        return false;
    }
    if (newItem) {
        newItem.c_mk_userno = loginInfo.sUser;
        newItem.c_submit_status = '0';
        newItem.c_mk_dt = dayjs().format('YYYY-MM-DD HH:mm:ss.SSS');
    }
    const req = {
        NewList: [],
        ModifiedList: [mainData.value],
        DelList: [],
        TableName: "tb_io_rec",
        PrimaryKeys: ["c_tenant_id", "c_id"],
        ChildData: [{
            ChildTableName: "tb_io_rec_g_middle",
            ParentTableName: "tb_io_rec",
            ChildColumnNames: ["c_id"],
            ParentColumnNames: ["c_id"],
            ChildSaveModel: {
                NewList: newItem ? [newItem] : [],
                ModifiedList: modifiedItem ? [modifiedItem] : [],
                DelList: delItem ? [delItem] : [],
                TableName: "tb_io_rec_g_middle",
                PrimaryKeys: ["c_tenant_id", "c_id", "c_gsort", "c_mk_dt", "c_mk_userno", "c_submit_status"],
            }
        }],
        BillSet: {
            BillIdKeyValue: {
                key: "c_id",
                value: mainData.value.c_id
            },
            BillVariable: "",
            TableName: "tb_io_rec",
            BillName: "商品验收单中间表"
        },
        TimeOut: 600
    };
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单中间表', 'EnjoyBillSaveNew', req, '701');
    console.log("result", result)
    await uni.showToast({
        duration: 2000,
        icon: 'none',
        title: `保存成功`
    });
    return true;
};

const submitBill = async () => {
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单中间表', 'EnjoyBillSubmit', mainData.value.c_id, '701');
    if (!result.Result) {
        await uni.showToast({
            duration: 3000,
            icon: 'none',
            title: result.Error.Message
        });
        return false;
    }

    await uni.showToast({
        duration: 2000,
        icon: 'none',
        title: `提交成功`
    });

    return true;
};
const canOverOrderValidate = async (ccode, orderN, recN) => {
    if (mainData.value.c_price_type !== '9' && recN > orderN) {
        //是否可超收的品类
        if (sysConfig.value.canOverOrderClass.some(c => ccode.startsWith(c.c_id) || c.c_id.startsWith(ccode))) {
            const rate = isNaN(sysConfig.value.recOverOrderRate) ? 0 : sysConfig.value.recOverOrderRate;
            const maxN = (orderN * (1 + rate * 0.01)).toFixed(3);
            if (recN > maxN) {
                await uni.showToast({
                    duration: 3000,
                    icon: 'none',
                    title: `验收数量超过允许的超收比例${sysConfig.value.recOverOrderRate}%，订货数量${orderN} 验收数量${recN},最多可验收数量${maxN}`
                });
                return false;
            }
        } else {
            await uni.showToast({
                duration: 3000,
                icon: 'none',
                title: `不允许超订单数量验收,订货数量${orderN} 验收数量${recN}`
            });
            return false;
        }
    }
    return true;
};
/**
 * 计算当前金额
 */
const calcRowAmount = async () => {
    currentGds.value.c_at_pay = calcAtInByPt({ c_pt: currentGds.value.c_pt_pay, c_n: currentGds.value.c_n });
    currentGds.value.c_at_in = calcAtInByPt({ c_pt: currentGds.value.c_pt_in, c_n: currentGds.value.c_n });
    currentGds.value.c_aet_pay = calcAtInByPt({ c_pt: currentGds.value.c_pet_pay, c_n: currentGds.value.c_n });
    currentGds.value.c_at_sale = calcAtInByPt({ c_pt: currentGds.value.c_price, c_n: currentGds.value.c_n });
    // const itemIndex = detailData.value.findIndex(i => i.c_gcode === currentGds.value.c_gcode);
    // if (itemIndex !== -1) {
    //     detailData.value[itemIndex] = currentGds.value; // 更新原数据
    // }
    // calcMainAmount();
};
const calcMainAmount = async () => {
    mainData.value.c_sku_rec = detailData.value.filter(i => i.c_n > 0 || i.c_n_free > 0).map(i => i.c_gcode).reduce((pre, cur) => pre.includes(cur) ? pre : [...pre, cur], []).length;
    mainData.value.c_n_rec = detailData.value.reduce((pre, current) => pre + (Number(current.c_n) ?? 0) + (Number(current.c_n_free) ?? 0), 0);
    mainData.value.c_at_pay_rec = detailData.value.reduce((pre, current) => pre + current.c_at_pay, 0);
    mainData.value.c_aet_pay_rec = detailData.value.reduce((pre, current) => pre + current.c_aet_pay, 0);
    mainData.value.c_at_in_rec = detailData.value.reduce((pre, current) => pre + current.c_at_in, 0);
    mainData.value.c_at_sale_rec = detailData.value.reduce((pre, current) => pre + current.c_at_sale, 0);
    c_sku_rec_total.value = listManager.value.reduce((pre, current) => pre + (current.c_n > 0 || current.c_n_free > 0), 0);
    c_n_rec_total.value = listManager.value.reduce((pre, current) => pre + (current.c_n ?? 0), 0);
    c_n_rec_free_total.value = listManager.value.reduce((pre, current) => pre + (current.c_n_free ?? 0), 0);
};
const converOdUnit = async (odUnit) => {
    let unit = 'd';
    switch (odUnit) {
        case 'D':
            unit = 'd'
            break;
        case 'M':
            unit = 'M'
            break;
        case 'Y':
            unit = 'y'
            break;
    }
    return unit
};
const validateProductDate = async (productDt) => {
    //如果保质期大于0
    if ((currentGds.value.c_od_day ?? 0) > 0) {
        //到期日期
        let expiredDt = dateAdd(currentGds.value.c_od_day, productDt, await converOdUnit(currentGds.value.c_od_unit))
        expiredDt = dateAdd(-1, expiredDt);

        const today = dayjs().format('YYYY-MM-DD');
        //留存天数
        const expiredDays = dateDiff(expiredDt, today);
        if (expiredDays <= 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '商品已过保质期，不允许收货，请确认！'
            });
            return false;
        }

        if (currentGds.value.c_od_warning_day) {
            if (expiredDays <= currentGds.value.c_od_warning_day) {
                await uni.showToast({
                    duration: 3000,
                    icon: 'none',
                    title: `商品临近保质期，不允许收货！可留存天数（限用日期-收货日期）小于保质期报警天数：${currentGds.value.c_od_warning_day},请确认`
                });
                return false;
            }
        }

        if (!isNaN(sysConfig.value.minExpiredPercent) && sysConfig.value.minExpiredPercent !== 0) {
            if (expiredDays / currentGds.value.c_od_day * 100 < sysConfig.value.minExpiredPercent) {
                await uni.showToast({
                    duration: 3000,
                    icon: 'none',
                    title: `商品临近保质期，不允许收货！可留存天数（限用日期-收货日期）保质期占比低于最低要求${sysConfig.value.minExpiredPercent}%，请确认！`
                });
                return false;
            }
        }
        if (!isNaN(sysConfig.value.exceedOutDate) && sysConfig.value.exceedOutDate < currentGds.value.c_od_day) {
            if (expiredDays < sysConfig.value.exceedOutDate) {
                await uni.showToast({
                    duration: 3000,
                    icon: 'none',
                    title: `商品临近保质期，不允许收货！可留存天数（限用日期-收货日期）小于保质期报警天数：${sysConfig.value.exceedOutDate},请确认`
                });
                return false;
            }
        }
        currentGds.value.c_expired_dt = expiredDt;
        currentGds.value.c_product_dt = productDt;
    }
    return true;
};
const productDtChanged = async (value) => {
    const result = await validateProductDt(value);
    if (!result) {
        currentGds.value.c_product_dt = null;
        return;
    }
    const itemIndex = detailData.value.findIndex(i => i.c_barcode === currentGds.value.c_barcode);
    if (itemIndex !== -1) {
        detailData.value[itemIndex] = currentGds.value;
    }
};

const expiredDtChanged = async (value) => {
    const result = await validateExpiredDt(value);
    if (!result) {
        currentGds.value.c_expired_dt = null;
        return;
    }
    const itemIndex = detailData.value.findIndex(i => i.c_barcode === currentGds.value.c_barcode);
    if (itemIndex !== -1) {
        detailData.value[itemIndex] = currentGds.value;
    }
};
const validateProductDt = async (value) => {
    if (!value) {
        // await uni.showToast({
        //     duration: 2000,
        //     icon: 'none',
        //     title: '生产日期不能为空！'
        // });
        return false;
    }
    const productDt = value;
    const today = dayjs().format('YYYY-MM-DD');
    if (mainData.value.c_rec_dt) {
        if (mainData.value.c_rec_dt < productDt) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '生产日期不可晚于收货日期！'
            });
            return false;
        }
    } else {
        if (dateDiff(productDt, today) > 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '生产日期不能晚于今天!'
            });
            return false;
        }
    }
    if ((currentGds.value.c_od_day ?? 0) === 0) {
        if (currentGds.value.c_expired_dt && dateDiff(productDt, currentGds.value.c_expired_dt) > 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '限用日期不能早于生产日期!'
            });
            return false;
        }
    }

    // 验证 生产日期是否早于历史验收的生产日期
    if (sysConfig.value.productDateCtrl == '1' || sysConfig.value.productDateCtrl == '2') {
        // 供应商、商品、生产日期
        const rep = await rdsRequestAsync(rdsUrl.scApi, '商品验收单', 'QueryRecGaByCodePrv', { gcode: currentGds.value.c_gcode, provider: mainData.value.c_provider }, 'S01');
        if (rep.HasException) {
            await uni.showToast({
                duration: 2500,
                icon: 'none',
                title: rep.Exception.Message
            });
            return;
        }
        if (rep.ObjectData && rep.ObjectData?.c_product_dt && productDt < dayjs(rep.ObjectData?.c_product_dt).format('YYYY-MM-DD')) {
            await uni.showToast({
                duration: 2500,
                icon: 'none',
                title: `商品生产日期[${productDt}]早于本商品在验收单[${rep.ObjectData.c_id}]的生产日期[${dayjs(rep.ObjectData?.c_product_dt).format('YYYY-MM-DD')}]!`
            });
            if (sysConfig.value.productDateCtrl === '2') {
                return;
            }
        }
    }

    const result = await validateProductDate(productDt)
    return result;
};
const validateExpiredDt = async (value) => {
    if (!value) {
        // await uni.showToast({
        //     duration: 2000,
        //     icon: 'none',
        //     title: '限用日期不能为空！'
        // });
        return false;
    }
    const today = dayjs().format('YYYY-MM-DD');
    const expiredDt = value;
    if (today > expiredDt) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '限用日期不能早于今天!'
        });
        return false;
    }
    if ((currentGds.value.c_od_day ?? 0) === 0) {
        if (currentGds.value.c_product_dt && dateDiff(currentGds.value.c_product_dt, expiredDt) > 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '生产日期不能晚于限用日期!'
            });
            return false;
        }
    }

    if (currentGds.value.c_od_day) {
        let productDt = dateAdd((currentGds.value.c_od_day) * -1, expiredDt, converOdUnit(currentGds.value.c_od_unit), 'd');
        if (mainData.value.c_rec_dt) {
            if (productDt > mainData.value.c_rec_dt) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: `商品生产日期不可晚于收货！根据商品保质期反算生产日期为[${productDt}]！`
                });
                return false;
            }
        } else if (productDt > today) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: `商品生产日期不可晚于今天！根据商品保质期反算生产日期为[${productDt}]！`
            });
            return false;
        }
        const result = await validateProductDate(productDt)
        return result
    }
    return true;
};
/**
 * 验证保质期大于0的商品(有收获数量的商品)，生产日期必填（例外部门除外）
 */
const validateProduceDt = async () => {
    let validated = true;
    let msg = ''

    let mustInputPdtGcodes = []
    let mustInputPdtIds = []
    listManager.value.forEach(i => {
        //重置错误信息
        if (i.c_err_msg) {
            i.c_err_msg = null;
        }
        if (sysConfig.value.isMustInputPdt === '1' &&//参数：有保质期商品是否必须录入生产日期
            i.c_od_day > 0 &&//保质期大于0
            !i.c_product_dt &&//生产日期为空
            //管易通能录入负数，所以不判断
            // (i.c_n_free > 0 || //赠品收获数量
            //     i.c_n > 0) &&//收货数量
            !sysConfig.value.mustInputPdtExceptAdnos.some(adno => i.c_adno.startsWith(adno.value)) //排除例外部门的
        ) {
            const err = [{ c_msg_err: '商品有保质期管理，请录入生产日期' }]
            i.c_err_msg = JSON.stringify(err)
            mustInputPdtIds.push(i.c_id);
            mustInputPdtGcodes.push(i.c_gcode);
        }
    });

    const strGcode = mustInputPdtGcodes.join(',');
    if (strGcode) {
        msg = `保存失败！以下商品有保质期管理，请录入生产日期！商品编码：${strGcode}`;
        validated = false;
    }

    return { validated, msg };
};
const change = async (e) => {
    isOpened.value = e;
    console.log('返回：', e);
};
const bindClick = async (e, index) => {
    console.log("e,index", e, index);
    await uni.showModal({
        title: ' 提示',
        content: '您确定要删除数据吗？',
        showCancel: true,
        success: async (res) => {
            if (res.confirm) {
                const delItem = listManager.value[index];
                await saveBillMiddle({ delItem: delItem });
                await billQueryMiddle('0');
                const recNewListIndex = recNewList.value.findIndex(item => item.c_gcode === delItem.c_gcode && item.c_barcode === delItem.c_barcode && item.c_gsort === delItem.c_gsort);
                recNewList.value.splice(recNewListIndex, 1);
                // await saveBill({ delItem: listManager.value[index] });
                // await billQuery();
                // delList.push(detailData.value[index]);
                // detailData.value.splice(index, 1);
                // await calcMainAmount();
            }
        }
    });
};
const validateGdsStore = async (param) => {
    const result = await rdsRequestAsync(rdsUrl.scApi, '商品验收单', 'ValidateGdsStore', { gcode: param.c_gcode, adno: '', storeId: sUserStore.value }, '701');
    if (result.HasException) {
        await uni.showToast({
            duration: 3000,
            icon: 'none',
            title: result.Error.Message
        });
        return false;
    }
    return result.ObjectData[0];
};


// clickLeft() {
//     if(isModified){
//         await uni.showModal({
//             title: '提示',
//             content: '模块存在修改的数据，您确定要丢弃修改的数据？',
//             success: (res) => {
//                 if (res.confirm) {
//                     uniBack();
//                 }
//             }
//         });
//     }else{
//         uniBack();
//     }
// },
// async onBackPress(e) {
//     console.log('onBackPress', e);
//     if (e.from === 'navigateBack') {
//         if (isModified) {
//             async function a() {
//                 return new Promise((resolve) => {
//                     await uni.showModal({
//                         title: '提示',
//                         content: '模块存在修改的数据，您确定要丢弃修改的数据？',
//                         success: (res) => {
//                             if (res.confirm) {
//                                 resolve(false);
//                             } else {
//                                 resolve(true);
//                             }
//                         }
//                     });
//                 });
//             }
//             let flag = await a();
//             console.log('flag', flag);
//             return true;
//         } else {
//             return false;
//         }
//     }
// };

const onClickSubmitDetail = async (e) => {
    euiNavBar.value.closeDrawer();
    await uni.navigateTo({
        url: './submitDetail?c_id=' + mainData.value.c_id + '&storeId=' + mainData.value.c_store_id
    });
};
const enjoyConfirm = async (e) => {
    console.log('enjoyConfirm', e);
    return new Promise((resolve) => {
        uni.showModal({
            title: '提示',
            content: e,
            success: (res) => {
                if (res.confirm) {
                    resolve(true);
                } else {
                    resolve(false);
                }
            }
        });
    });
}
</script>

<style lang="scss" scoped>
@import '@/static/font/enjoyicon/iconfont.css';
@import '../../../main.scss';

::v-deep .white-main {
    margin: 20rpx 0;
}

.content-img {
    background-color: #FFFFFF;
    background-size: 100% 176rpx;
    background-repeat: no-repeat;
    width: 100%;
}

.custom-menu {
    border-top: 1px solid rgba(0, 0, 0, .1);
    display: flex;
    flex: 1;
    width: 100%;
    justify-content: flex-start;
}

.extra-view {
    margin-right: 30rpx;
    font-size: 12px;
    color: #0099ff
}

.bt-button {
    background-color: #FFFFFF;
    padding: 10rpx 0rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.popup-icon-btn {
    display: flex;
    padding: 10px;
    margin: 5px;
    color: #333333;
    text-align: center;
    flex-direction: column;
}

.popup-icon-btn uni-icon {
    margin: 0 auto;
    background: #ffffff;
    border-radius: 50%;
    font-size: 1.2em;
    width: 42px;
    height: 42px;
    line-height: 42px;
    text-align: center;
}

.popup-icon-btn uni-text {
    font-size: 0.8em;
    padding: 0.2em 0;
    line-height: 1.4em;
    width: 52px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

// 业务自定义
.icon_new_count {
    color: #00aaff;
}

.top-view {
    width: 100%;
    height: 88rpx;
    background: #FFFFFF;
}

.footer-view {
    width: 100%;
    flex: 1;
}

.m-main-top {
    width: 100%;
    display: grid;
    grid-template-columns: 51% 49%;
    font-size: 12px;
}

.m-list-top {
    width: 100%;
    display: grid;
    grid-template-columns: 51% 49%;
    font-size: 12px;
    padding: 10rpx 0rpx;
}


.template_title_bottem {
    display: flex;
    flex-direction: revert;
    justify-content: space-between;
    margin: 10rpx 16rpx;
    padding: 10rpx;
    border-radius: 20rpx;
    border: 2rpx solid $uni-bg-color-hover;
}


.eui-count-input-content {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    background-color: #ffffff;
    //border-radius: $uni-border-radius-max;
}

.eui-count-input-content:last-child {
    margin-bottom: 180rpx; // 保持和底部一定的距离
}

.with-current-gds {
    background-color: #FDFFC2E0;
    //设置元素置顶
    position: relative;
}

.popup-content {
    align-items: center;
    justify-content: flex-start;
    flex-direction: column;
    padding: 0 20rpx 20rpx 20rpx;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
}

.image-min {
    width: 100%;
    height: 150rpx;
    opacity: 0.6;
    margin-top: -20rpx;
}

.no-data-text {
    text-align: center;
    color: #cccccc;
    font-size: 26rpx;
    margin-top: -20rpx;
}

.popup-height {
    width: 200px;
}

.popup-content-message {
    align-items: center;
    justify-content: left;
    flex-direction: column;
    padding: 0 20rpx 20rpx 20rpx;
    width: 600rpx;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
}

.popup-title {
    width: 100%;
    height: 84rpx;
    background: #FFFFFF;
    border-radius: 40rpx 40rpx 0 0;
    display: flex;
    justify-content: center;
    align-items: center;
    color: $uni-text-color-secondary;
    font-size: $uni-font-size-level1;
    line-height: 45rpx;
    text-align: center;
    position: relative;
}
</style>
